

//
//  NSMutableArray+exchange.m
//  动态创建对象
//
//  Created by MyMac on 15/8/28.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "NSMutableArray+exchange.h"
#import <objc/runtime.h>

@implementation NSMutableArray (exchange)
//+(void)load
//{
//    Method old=class_getInstanceMethod(self, @selector(addObject:));
//    Method new=class_getInstanceMethod(self, @selector(loadNewAddObject:));
//替换的原理
////    IMP imp1=method_getImplementation(old);
////    IMP imp2=method_getImplementation(new);
////    method_setImplementation(old, imp2);
////    method_setImplementation(new, imp1);
//   // method_exchangeImplementations(old, new);
//
//
//
//}
+ (void)load {
    static dispatch_once_t onveToken;
    dispatch_once(&onveToken, ^{
        
   
    //不知怎么了，，，系统方法替换不了，，，exchangeAdd执行的是addObject，，，但addObject执行的不是exchangeAdd方法
    Method old=class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(addObject:));
    Method new=class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(exchangeAdd:));
//    IMP newIMP=method_getImplementation(new);
//    IMP oldIMP=method_getImplementation(old);
   // BOOL isAdd=class_addMethod([self class], @selector(addObject:), newIMP, method_getTypeEncoding(new));
    //if(!isAdd){
    
     //   class_replaceMethod([self class], @selector(exchangeAdd:), oldIMP, method_getTypeEncoding(old));
    
    
    
    //}else{
    
    
    method_exchangeImplementations(old, new);
   // }
    
    
    
    
    
    
    //自定义的方法可以实现完全替换，loadNewAddObject执行logAddObject，，logAddObject执行loadNewAddObject
//    Method loadNewAddObject = class_getInstanceMethod([NSMutableArray class], @selector(loadNewAddObject:));
//    Method logAddObject = class_getInstanceMethod([NSMutableArray class], @selector(logAddObject:));
//    method_exchangeImplementations(loadNewAddObject,logAddObject);
         });
    
}

- (void)logAddObject:(id)aObject {
    //不会实现递归，因为logAddObject执行的是loadNewAddObject方法
    //[self logAddObject:aObject];
    NSLog(@"%@", aObject);
}
-(void)loadNewAddObject:(id)object
{
    
    NSLog(@"%@",object);
    
    
}
-(void)exchangeAdd:(id)object
{
    if (!object) {
        return;
    }
    [self exchangeAdd:object];
   // NSLog(@"%@",object);

}
@end
